package com.it.config;

import cn.hutool.json.JSONUtil;
import com.it.vo.Response;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 处理认证失败的逻辑
 *
 * @author: Coke
 * @DateTime: 2023/11/19/15:05
 **/
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    // 处理认证失败的逻辑
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 设置响应的内容类型为JSON，使用UTF-8字符集
        response.setContentType("application/json;charset=UTF-8");
        
        // 获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        
        // 构建错误响应，如果异常消息是"Bad credentials"，则返回"用户名或密码不正确"，否则返回异常消息
        Response<?> error = Response.error("Bad credentials".equals(exception.getMessage()) ? "用户名或密码不正确" : exception.getMessage());
        
        // 将错误响应转换为JSON字符串，并写入输出流中
        outputStream.write(JSONUtil.toJsonStr(error).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
